package com.lanxiao.cloud.gateway.handler;

import com.lanxiao.cloud.common.core.exception.BusinessException;
import java.nio.charset.StandardCharsets;
import org.apache.dubbo.rpc.RpcException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ：qiaoliang
 * @date ：2021-09-10
 */
@Order(-1)
@Configuration
public class GatewayExceptionHandler  implements ErrorWebExceptionHandler {

  @Override
  public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    ServerHttpResponse response = exchange.getResponse();
    if (exchange.getResponse().isCommitted()) {
      return Mono.error(ex);
    }
    if(ex instanceof BusinessException) {
      BusinessException businessException = (BusinessException)ex;
      return this.webFluxResponseWriter(response,
          HttpStatus.valueOf(businessException.getErrorType().getCode()),
          businessException.getErrorType().getMessage());
    }

    return this.webFluxResponseWriter(response, HttpStatus.CONFLICT, "服务器开小差了.");
  }

  private Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus code, String value) {
    response.setStatusCode(code);
    final byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
    DataBuffer buffer = response.bufferFactory().wrap(bytes);
    //指定编码，否则在浏览器中会中文乱码
    response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
    return response.writeWith(Mono.just(buffer));
  }

}
